package com.example.esp8266_wifi_control.utils;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class SocketUtil {

    private static final String TAG = "SocketUtil";

    private Context context;

    private Socket socket;

    public SocketUtil(Context context) {
        this.context = context;
    }

    public void initTcpSocket(String host, int port) {
        try {
            socket = new Socket(host, port);
        } catch (IOException e) {
            Log.e(TAG, "initTcpSocket: TCP初始化失败", e);
            Toast.makeText(this.context, "TCP初始化失败！", Toast.LENGTH_SHORT).show();
        }
    }

    public void send(String msg, MessageCallback callback) {
        if (socket == null) {
            showToast("请先链接设备");
        }
        try {
            OutputStream os = socket.getOutputStream();
            os.write(msg.getBytes(StandardCharsets.UTF_8));
            os.flush();
        } catch (IOException e) {
            Log.e(TAG, "send: error", e);
            this.showToast("发送失败！");
        }
    }

    private void showToast(String text) {
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
            }
        });
    }

    public interface MessageCallback {

        void handler(String remoteAddress, String msg);

        void udpMsg(String msg);

    }
}
